//
//  SJ_HomeViewController.m
//  CarFile
//
//  Created by 陈浩 on 2018/2/5.
//  Copyright © 2018年 陈浩. All rights reserved.
//

#import "SJ_HomeViewController.h"
#import "CHQueryViewController.h"
#import "CHScrollView.h"
#import "CHRollView.h"
#import "CHHomeViewCell.h"
#import "CHPopView.h"
#import "CHEvaluationListController.h"
#import "CHComplainCountController.h"
#import "CHAccountViewController.h"
#import "CHInformViewController.h"
#import "CHInformDetailController.h"
#import "CHExceptionListController.h"
#import "CHYYGLViewController.h"
#import "CHCompanyQueryController.h"
#import "SelectAlert.h"
#import "PJ_Model.h"
#import "CHNoticeModel.h"
#import "JXButton.h"
#import "CHTitleView.h"
#import "UIButton+HQCustomIcon.h"
#import "HJDropDownMenu.h"
#import "CountyModel.h"
#import "SearchCompanyController.h"
#import "GovrecordsViewController.h"
#import "CHDockingViewController.h"
#import "LMJDropdownMenu.h"
@interface SJ_HomeViewController ()<UICollectionViewDelegate,UICollectionViewDataSource,UIScrollViewDelegate,LMJDropdownMenuDelegate>
@property (nonatomic ,copy) NSString *startTime;
@property (nonatomic ,copy) NSString *endTime;
@property (nonatomic ,copy) NSString *remarksPath;
@property (nonatomic ,strong) NSMutableArray *datas;
@property (nonatomic ,strong) UIView *bgView;
@property (nonatomic ,strong) CHScrollView *scrollView;
@property (nonatomic ,strong) UIView *headerView;
@property (nonatomic ,strong) CHRollView *rollView;
@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) UIView *mainView;
@property (nonatomic ,strong) CHPopView *popView;
@property (nonatomic ,strong) NSArray *titles;
@property (nonatomic ,strong) NSArray *resultArr;
@property (nonatomic ,strong) UIView *menuView;
@property (nonatomic ,strong) NSArray *noticeTitles;
@property (nonatomic ,strong) NSMutableArray *noticeArr;
@property (nonatomic ,strong) UIAlertView *alertView;
@property (nonatomic ,strong) UIScrollView *mainScrollView;
@property (nonatomic ,strong) UIView *indicatorView;
@property (nonatomic ,strong) UIScrollView *queryScrollView;
@property (nonatomic ,strong) UIView *queryView;
@property (nonatomic ,strong) UIView *qyView;
@property (nonatomic ,strong) UIView *repairView;
@property (nonatomic ,strong) UIButton *selectedBtn;
@property (nonatomic ,strong) NSMutableArray *citys;
@property (nonatomic ,strong) NSMutableArray *lowerCitys;
@property (nonatomic ,strong) LMJDropdownMenu *yearMenu;
@property (nonatomic ,strong) LMJDropdownMenu *areanMenu;
@property (nonatomic ,strong) UITextField *wxqyField;
@property (nonatomic ,strong) UITextField *majorField;
@property (nonatomic ,strong) UITextField *carnoField;
@property (nonatomic ,strong) UITextField *vinField;
@property (nonatomic ,copy) NSString *areaid;
@property (nonatomic ,assign) BOOL isSearchCompany;
@end

@implementation SJ_HomeViewController

-(NSMutableArray *)lowerCitys{
    if (!_lowerCitys) {
        _lowerCitys = [NSMutableArray array];
    }
    return _lowerCitys;
}

-(NSMutableArray *)citys{
    if (!_citys) {
        _citys = [NSMutableArray array];
    }
    return _citys;
}

-(NSMutableArray *)noticeArr{
    if (!_noticeArr) {
        _noticeArr = [NSMutableArray array];
    }
    return _noticeArr;
}


-(NSMutableArray *)datas{
    
    if (!_datas) {
        _datas = [NSMutableArray array];
    }
    return _datas;
}


-(NSArray *)resultDic{
    
    if (!_resultArr) {
        _resultArr = [NSArray array];
    }
    return _resultArr;
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = NO;
    self.view.backgroundColor = KRGB(230, 243, 252);
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    self.titles = @[@"维修车辆",@"维修量",@"覆盖城市",@"维修企业"];
    
    self.startTime =[Util getStartTimeWithNumber:7];
    self.endTime = [Util getCurrentTime];
    _isSearchCompany = YES;
    
    BOOL isLogin = [Util boolForkey:@"islogin"];
    //    NSString *serviceURL = (NSString *)[Util getValue:@"serviceURL"];
    if (isLogin ) {
        //    检查是否需要更新版本
        [self checkVersion];
    }
    
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
//

    
    [MBProgressHUD showMessage:@"加载中..."];
    
    [self setupLeftBarButtonItem];
    
    [self setupMainScrollView];
    
    [self setupHeaderView];
    
    //  创建通知信息滚动视图
    [self setupRollView];
    
    //  创建查询菜单主体
    [self setupMainView];
    
    //   添加条件查询view
    [self setupQueryView];
    
    //   请求网络数据
    [self getNetworkingData];
    
}

-(void)setupQueryView{
    UIView *queryView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.collectionView.frame)+10, UIScreenW, 320)];
    queryView.backgroundColor = [UIColor whiteColor];
    [self.mainScrollView addSubview:queryView];
    self.queryView = queryView;
    
    UIView *signView = [[UIView alloc] initWithFrame:CGRectMake(12, 13*ScaleY, 2, 18*ScaleY)];
    signView.backgroundColor = KRGB(9, 142, 221);
    [queryView addSubview:signView];
    
    
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(signView.frame)+5, 0, UIScreenW/2, 44*ScaleY)];
    titleLabel.textColor = KRGB(9,142, 221);
    titleLabel.text = @"条件查询";
    titleLabel.font =Font(16);
    [queryView addSubview:titleLabel];
    
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(titleLabel.frame), UIScreenW, 1)];
    line.backgroundColor = [UIColor colorWithHexString:@"f3f3f3" alpha:1.0f];
    [queryView addSubview:line];
    
    
    UIButton *qyBtn = [[UIButton alloc] initWithFrame:CGRectMake((UIScreenW - 170)/2,CGRectGetMaxY(line.frame)+ 10, 70, 30)];
    qyBtn.titleLabel.font =Font(16);
    qyBtn.enabled = NO;
    self.selectedBtn = qyBtn;
    qyBtn.tag = 100;
    [qyBtn setTitle:@"企业查询" forState:UIControlStateNormal];
    [qyBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [qyBtn setTitleColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f] forState:UIControlStateDisabled];
    [qyBtn addTarget:self action:@selector(queryAction:) forControlEvents:UIControlEventTouchUpInside];
    [queryView addSubview:qyBtn];
    
    UIButton *repairBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(qyBtn.frame)+30, CGRectGetMaxY(line.frame)+10, 70, 30)];
    repairBtn.titleLabel.font =Font(16);
    repairBtn.tag = 101;
    [repairBtn setTitle:@"维修记录" forState:UIControlStateNormal];
    [repairBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [repairBtn setTitleColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f] forState:UIControlStateDisabled];
    [repairBtn addTarget:self action:@selector(queryAction:) forControlEvents:UIControlEventTouchUpInside];
    [queryView addSubview:repairBtn];
    
    UIView *indicatorView = [[UIView alloc] initWithFrame:CGRectMake(qyBtn.x, CGRectGetMaxY(qyBtn.frame), qyBtn.w, 1)];
    indicatorView.backgroundColor = [UIColor colorWithHexString:@"098edd" alpha:1.0f];
    [queryView addSubview:indicatorView];
    self.indicatorView = indicatorView;
    
    [self addQyView];
    
    [self addRepairView];
}

-(void)addQyView{
    
    UIView *qyView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.indicatorView.frame), UIScreenW, self.queryView.h - CGRectGetMaxY(self.indicatorView.frame))];
    [self.queryView addSubview:qyView];
    self.qyView = qyView;
    
    UILabel *areaLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 120, 35)];
    areaLabel.text = @"区域选择：";
    areaLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    areaLabel.textAlignment = NSTextAlignmentRight;
    areaLabel.font = Font(16);
    [qyView addSubview:areaLabel];
    
    LMJDropdownMenu * yearMenu = [[LMJDropdownMenu alloc] initWithFrame:CGRectMake(125, 20, (UIScreenW - 30 -125)/2, 35)];
    yearMenu.delegate = self;
    [yearMenu.mainBtn setTitle:@"选择市" forState:UIControlStateNormal];
    [qyView addSubview:yearMenu];
    self.yearMenu = yearMenu;
    
    
    LMJDropdownMenu * areanMenu = [[LMJDropdownMenu alloc] initWithFrame:CGRectMake(CGRectGetMaxX(yearMenu.frame)+10, 20, (UIScreenW - 30 -125)/2, 35)];
    areanMenu.delegate = self;
    [areanMenu.mainBtn setTitle:@"选择区" forState:UIControlStateNormal];
    [qyView addSubview:areanMenu];
    self.areanMenu = areanMenu;
    
    
    UILabel *wxqyLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(areaLabel.frame) +10, 120, 35)];
    wxqyLabel.text = @"维修企业名称：";
    wxqyLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    wxqyLabel.textAlignment = NSTextAlignmentRight;
    wxqyLabel.font = Font(16);
    [qyView addSubview:wxqyLabel];
    
    UITextField *wxqyField = [[UITextField alloc] initWithFrame:CGRectMake(125, wxqyLabel.y, UIScreenW - 125- 20, 35)];
    wxqyField.font = Font(16);
    wxqyField.borderStyle = UITextBorderStyleRoundedRect;
    [qyView addSubview:wxqyField];
    self.wxqyField = wxqyField;
    
    UILabel *majorLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(wxqyLabel.frame) +10, 120, 35)];
    majorLabel.text = @"主修品牌：";
    majorLabel.textColor = [UIColor colorWithHexString:@"333333" alpha:1.0f];
    majorLabel.textAlignment = NSTextAlignmentRight;
    majorLabel.font = Font(16);
    [qyView addSubview:majorLabel];
    
    
    UITextField *majorField = [[UITextField alloc] initWithFrame:CGRectMake(125, majorLabel.y, UIScreenW - 125- 20, 35)];
    majorField.font = Font(16);
    majorField.borderStyle = UITextBorderStyleRoundedRect;
    [qyView addSubview:majorField];
    self.majorField = majorField;
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(majorField.frame)+20, UIScreenW -24, 44)];
    searchBtn.titleLabel.font = Font(16);
    searchBtn.layer.cornerRadius = 7.5;
    searchBtn.layer.masksToBounds = YES;
    [searchBtn setBackgroundColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f]];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn setTitle:@"立即查询" forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [qyView addSubview:searchBtn];
    
    
    self.mainScrollView.contentSize = CGSizeMake(UIScreenW , CGRectGetMaxY(self.queryView.frame));
    
}


-(void)addRepairView{
    
    UIView *repairView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.indicatorView.frame), UIScreenW, self.queryView.h - 80- CGRectGetMaxY(self.indicatorView.frame))];
    repairView.hidden = YES;
    [self.queryView addSubview:repairView];
    self.repairView = repairView;

    
    UILabel *carnoLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 20, 120, 35)];
    carnoLabel.text = @"车牌号码：";
    carnoLabel.textAlignment = NSTextAlignmentRight;
    carnoLabel.font = Font(16);
    [repairView addSubview:carnoLabel];
    
    UITextField *carnoField = [[UITextField alloc] initWithFrame:CGRectMake(125, 20, UIScreenW - 125- 20, 35)];
    carnoField.font = Font(16);
    carnoField.borderStyle = UITextBorderStyleRoundedRect;
    [repairView addSubview:carnoField];
    self.carnoField = carnoField;
    
    
    UILabel *vinLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(carnoLabel.frame)+10, 120, 35)];
    vinLabel.text = @"vin码：";
    vinLabel.textAlignment = NSTextAlignmentRight;
    vinLabel.font = Font(16);
    [repairView addSubview:vinLabel];
    
    UITextField *vinField = [[UITextField alloc] initWithFrame:CGRectMake(125, vinLabel.y, UIScreenW - 125- 20, 35)];
    vinField.font = Font(16);
    vinField.borderStyle = UITextBorderStyleRoundedRect;
    [repairView addSubview:vinField];
    self.vinField = vinField;
    
    UIButton *searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, CGRectGetMaxY(vinField.frame)+20, UIScreenW -24, 44)];
    searchBtn.titleLabel.font = Font(16);
    searchBtn.layer.cornerRadius = 7.5;
    searchBtn.userInteractionEnabled = YES;
    searchBtn.layer.masksToBounds = YES;
    [searchBtn setBackgroundColor:[UIColor colorWithHexString:@"098edd" alpha:1.0f]];
    [searchBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [searchBtn setTitle:@"立即查询" forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [repairView addSubview:searchBtn];
    
}



//  城市下拉列表
-(void)cityBtnClick{
    
    
    
}

//  区域下拉列表
-(void)areanBtnClick{
    
}


//  立即查询
-(void)searchBtnClick{

    if (_isSearchCompany) {
        if (_areaid.length == 0) {
            [MBProgressHUD showTipMessageInView:@"区域没有选择"];
            return;
        }
        SearchCompanyController *vc = [[SearchCompanyController alloc] init];
        vc.magorbrands = self.majorField.text;
        vc.company = self.wxqyField.text;
        vc.areaid = self.areaid;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        if (self.carnoField.text.length == 0 && self.vinField.text.length == 0) {
            [MBProgressHUD showTipMessageInView:@"车牌号或者vin码不能为空"];
            return;
        }
        GovrecordsViewController *vc = [[GovrecordsViewController alloc] init];
        vc.carno = self.carnoField.text;
        vc.carvin = self.vinField.text;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

-(void)queryAction:(UIButton *)btn{

    [self.view endEditing:YES];
    if (btn.tag == 100) {

        self.qyView.hidden = NO;
        self.repairView.hidden = YES;
        
    }else{
        
        self.qyView.hidden = YES;
        self.repairView.hidden = NO;

    }
    _isSearchCompany = btn.tag == 100 ? YES : NO;
    self.selectedBtn.enabled = YES;
    btn.enabled = NO;
    self.selectedBtn  = btn;
    
    [UIView animateWithDuration:0.2 animations:^{
        
        self.indicatorView.frame = CGRectMake(btn.x, CGRectGetMaxY(btn.frame), btn.w, 1);
        
    }];
    
}

-(void)setupMainScrollView{
    
    UIScrollView *mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, UIScreenH - 49)];
    mainScrollView.userInteractionEnabled = YES;
    mainScrollView.showsHorizontalScrollIndicator = NO;
    mainScrollView.showsVerticalScrollIndicator = NO;
    mainScrollView.delegate = self;
    
//    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
//    [mainScrollView addGestureRecognizer:tap];
//
    [self.view addSubview:mainScrollView];
    self.mainScrollView = mainScrollView;
    
    
}

//-(void)tapAction:(UITapGestureRecognizer *)tap{
//
//    [self.yearMenu hideDropDown];
//    [self.areanMenu hideDropDown];
//}


-(void)setupHeaderView{
    
    //    头部背景图片
    UIImageView *headerBgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW, 234*ScaleY)];
    headerBgView.userInteractionEnabled = YES;
    headerBgView.image = [UIImage imageNamed:@"banner"];
    [self.mainScrollView insertSubview:headerBgView atIndex:0];
    self.headerView = headerBgView;
    
    //    用户信息按钮
    UIButton *userBtn = [[UIButton alloc] initWithFrame:CGRectMake(12, 24, 21, 21)];
    [userBtn setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
    [userBtn addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    [headerBgView addSubview:userBtn];
    
    //    省份
    UILabel *areacnLabel = [[UILabel alloc] initWithFrame:CGRectMake(UIScreenW - 100, 22, 90, 30)];
    areacnLabel.font = Font(14);
    areacnLabel.text = [Globle getInstance].userInfoDic[@"areacn"];
    areacnLabel.textColor = [UIColor whiteColor];
    areacnLabel.textAlignment = NSTextAlignmentCenter;
    [headerBgView addSubview:areacnLabel];
    
    
    UIView *menuView = [[UIView alloc] initWithFrame:CGRectMake(12, 165*ScaleY, UIScreenW - 2 *12, 90*ScaleY)];
    menuView.backgroundColor = [UIColor whiteColor];
    menuView.layer.cornerRadius = 5;
    menuView.layer.masksToBounds = YES;
    menuView.layer.borderWidth = 0.5;
    menuView.layer.borderColor = [UIColor colorWithHexString:@"098edd" alpha:0.2f].CGColor;
    [headerBgView insertSubview:menuView atIndex:1];
    self.menuView = menuView;
    
    CGFloat marginW = (menuView.w - 4 *50*ScaleX)/5;
    NSArray *titleArr = @[@"联网对接",@"维修企业",@"异常企业",@"维修记录"];
    for (int i = 0; i< 4; i++) {
        JXButton *btn = [[JXButton alloc] initWithFrame:CGRectMake(marginW + i * (marginW + 50*ScaleX), 15*ScaleY, 50*ScaleX, 60*ScaleY)];
        btn.tag = i;
        [btn setTitle:[NSString stringWithFormat:@"%@",titleArr[i]] forState:0];
        [btn setTitleColor:[UIColor blackColor] forState:0];
        btn.titleLabel.font = Font(12);
        NSString *imgName = [NSString stringWithFormat:@"sj_home_menu_%d",i+1];
        [btn setImage:[UIImage imageNamed:imgName] forState:0];
        [btn addTarget:self action:@selector(menuBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [menuView addSubview:btn];
    }
    
}


-(void)menuBtnClick:(JXButton *)btn{
    if (btn.tag == 0) {
        
        id obj = [LongriseRouter openURL:@"CHDockingViewController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [self.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                
                params[@"title"] = @"联网对接情况";
                params[@"index"] = @"0";
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
    }else if (btn.tag == 1){
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXQY" object:nil];
        UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:2];
        UIViewController *vc = nav.topViewController;
        
        if ([vc isKindOfClass:[CHQueryViewController class]]) {
            [((CHQueryViewController *)vc) setMark:1];
        }
        self.tabBarController.selectedIndex = 2;
        
        
    }else if (btn.tag == 2){
        CHExceptionListController *vc = [[CHExceptionListController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }else if (btn.tag == 3) {
        
        [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXJL" object:nil];
        UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:2];
        UIViewController *vc = nav.topViewController;
        
        if ([vc isKindOfClass:[CHQueryViewController class]]) {
            [((CHQueryViewController *)vc) setMark:2];
        }
        self.tabBarController.selectedIndex = 2;
    }
    
}



-(void)setupLeftBarButtonItem{
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 21, 21)];
    [btn setImage:[UIImage imageNamed:@"user"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(leftBarButtonItemClick) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn];
    
    
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
    label.font = [UIFont systemFontOfSize:14];
    label.text = [Globle getInstance].userInfoDic[@"areacn"];
    label.textColor = [UIColor whiteColor];
    label.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:label];
    
}


#pragma mark - 搭建UI界面

-(void)setupMainView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.minimumInteritemSpacing = 1;
    flowLayout.itemSize = CGSizeMake(UIScreenW /2, 80 *ScaleY);
    UICollectionView *collectionView =  [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.bgView.frame)+10, UIScreenW, 160*ScaleY ) collectionViewLayout:flowLayout];
    
    collectionView.backgroundColor = [UIColor colorWithHexString:@"eeeef0" alpha:1.0];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.scrollEnabled = YES;
    collectionView.showsHorizontalScrollIndicator = NO;
    [collectionView registerClass:[CHHomeViewCell class] forCellWithReuseIdentifier:@"homeCell"];
    [self.mainScrollView addSubview:collectionView];
    self.collectionView = collectionView;
    
    
}



-(void)setupRollView{
    
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.menuView.frame) +10, UIScreenW , 44*ScaleY)];
    bgView.backgroundColor = [UIColor whiteColor];
    [self.mainScrollView addSubview:bgView];
    self.bgView = bgView;
    
    UIImageView *noticeImg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"notice"]];
    noticeImg.frame = CGRectMake(10, 14.5, 70*ScaleX, 15*ScaleY);
    [bgView addSubview:noticeImg];
    
    //分割线
    CALayer *line = [CALayer layer];
    line.backgroundColor = [UIColor colorWithHexString:@"ececec" alpha:1.0].CGColor;
    line.frame = CGRectMake(CGRectGetMaxX(noticeImg.frame) + 6.5, 12*ScaleY, 1, 20*ScaleY);
    [bgView.layer addSublayer:line];
    
    
    // 通知
    self.rollView = [[CHRollView alloc] initWithFrame:CGRectMake(CGRectGetMaxX(line.frame) +6.5, 0, UIScreenW - CGRectGetMaxX(line.frame) - 6.5-44*ScaleX, 44 *ScaleY)];
    //点击公告内容
    __weak __typeof(self)weakSelf = self;
    self.rollView.clickBlock = ^(NSInteger index) {
        
        id obj = [LongriseRouter openURL:@"CHInformDetailController"];
        if(obj && [obj isKindOfClass:[UIViewController class]])
        {
            UIViewController *vc = obj;
            [weakSelf.navigationController pushViewController:vc animated:YES];
        }
        
        //判断该类是否可以传参数
        if([LongriseRouter isImplLongriseRouterDelegaterWithObject:obj])
        {
            id<LongriseRouterDelegater> delegater = obj;
            if(delegater)
            {
                
                NSMutableDictionary *params = [NSMutableDictionary dictionary];
                params[@"model"] =  weakSelf.noticeArr[index];
                
                //进行传值，传入统一的block以供B进行回调
                [delegater setParams:params block:^(id obj) {
                    
                    
                }];
            }
        }
        
    };
    
    [bgView addSubview:self.rollView];
    
    UIButton *moreBtn = [[UIButton alloc] initWithFrame:CGRectMake(UIScreenW - 44*ScaleX, 0, 44*ScaleX, 44*ScaleY)];
    moreBtn.imageEdgeInsets = UIEdgeInsetsMake(15, 18, 15, 18);
    [moreBtn setImage:[UIImage imageNamed:@"right_arrow"] forState:UIControlStateNormal];
    [moreBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [moreBtn addTarget:self action:@selector(moreBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:moreBtn];
    
}


-(void)moreBtnClick{
    
    id obj = [LongriseRouter openURL:@"CHInformViewController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


-(void)setupScrollView{
    
    NSArray *datas = [NSArray arrayWithObjects:@[@"22"], nil];
    self.scrollView = [[CHScrollView alloc] initWithFrame:CGRectMake(0, 0, UIScreenW  , 180 * ScaleY) withDatas:datas];
    [self.view addSubview:self.scrollView];
    
}

-(void)leftBarButtonItemClick{
    
    id obj = [LongriseRouter openURL:@"CHAccountViewController"];
    if(obj && [obj isKindOfClass:[UIViewController class]])
    {
        UIViewController *vc = obj;
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


//   获取最近统计数据
-(void)getRecentStatisticsDataWithDays:(int)days{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"start"] =self.startTime;
    params[@"end"] = self.endTime;
    NSLog(@"%@",params);
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovtotle" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [MBProgressHUD hideHUD];
        NSLog(@"%@",result);
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            NSDictionary *dict = result[@"data"];
            self.resultArr = @[dict[@"repairnum"],dict[@"recordnum"],dict[@"citynum"],dict[@"comnum"]];
            
        }
        [self.collectionView reloadData];
    }];
    
}


-(void)getLowerCityListDataWithAreaid:(NSString *)areaid{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = areaid;
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:areaid encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    [[Globle getInstance].service requestWithServiceName:@"appgetcountys" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"城市列表%@",result);
        
        NSMutableArray *tempArr = [NSMutableArray array];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CountyModel *model = [CountyModel objectWithKeyValues:dict];
                [tempArr addObject:dict[@"acname"]];
                [self.lowerCitys addObject:model];
            }
            [self.areanMenu setMenuTitles:tempArr rowHeight:30];
        }
    }];
    
}



#pragma mark - 获取城市列表
-(void)getCountyListData{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"]
                       encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    
    NSLog(@"%@",params);
    [[Globle getInstance].service requestWithServiceName:@"appgetcountys" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"城市列表%@",result);
        
        NSMutableArray *tempArr = [NSMutableArray array];
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                
                CountyModel *model = [CountyModel objectWithKeyValues:dict];
                
                [tempArr addObject:dict[@"acname"]];
                [self.citys addObject:model];
            }
            [self.yearMenu setMenuTitles:tempArr rowHeight:30];
        }
    }];
    
}

-(void)getNoticeData{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"50";
    params[@"pagenum"] = @"1";
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [self.datas removeAllObjects];
        
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.noticeArr addObject:model];
                
                [self.datas addObject:dict[@"title"]];
            }
            self.rollView.dataArr = self.datas;
        }
    }];
}

//  获取下级区域
-(void)getLevelAreaData{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovarealist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            NSMutableArray *tempArr = [NSMutableArray array];
            NSMutableArray *areacns = [NSMutableArray array];
            for (NSDictionary *dict in result[@"data"][@"arealist"]) {
                PJ_Model *model = [PJ_Model objectWithKeyValues:dict];
                [tempArr addObject:model];
                [areacns addObject:dict[@"areacn"]];
            }
            [Globle getInstance].datas = tempArr;
            [Globle getInstance].areacns = areacns;
        }
        
    }];
    
}

//  获取从开始到当前的时间天数
-(int)getDays{
    
    
    //首先创建格式化对象
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //然后创建日期对象
    
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear = [[formatter stringFromDate:date] integerValue];
    
    NSDate *date1 = [dateFormatter dateFromString:[NSString stringWithFormat:@"%ld-01-01 00:00:00",currentYear]];
    
    //计算时间间隔（单位是秒）
    
    NSTimeInterval time = [date timeIntervalSinceDate:date1];
    
    //计算天数
    
    int days = ((int)time)/(3600*24);
    
    return days;
}


-(void)getAdvertList:(void(^)())finish{
    //网络请求..成功后调用一下finish,失败也调用finish
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"areaid"] = [Util getValue:@"areaid"];
    params[@"userflag"] = [Util getValue:@"userflag"];
    params[@"usertype"] = [Util getValue:@"usertype"];
    params[@"user"] = [Globle getInstance].user;
    params[@"sign"] = [DESCript encrypt:(NSString *)[Util getValue:@"areaid"] encryptOrDecrypt:kCCEncrypt key:[Globle getInstance].key];
    params[@"pagesize"] = @"50";
    params[@"pagenum"] = @"1";
    params[@"type"] = @"3";
    [[Globle getInstance].service requestWithServiceName:@"lcipappgovnewslist" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        [self.datas removeAllObjects];
        
        
        if ([result[@"code"] isEqualToString:@"1"]) {
            
            finish();
            
            for (NSDictionary *dict in result[@"data"][@"list"]) {
                CHNoticeModel *model = [CHNoticeModel objectWithKeyValues:dict];
                [self.noticeArr addObject:model];
                
                [self.datas addObject:dict[@"title"]];
            }
            self.rollView.dataArr = self.datas;
        }
    }];
    
}




- (void)getNetworkingData{
    [MBProgressHUD showMessage:@"加载中..."];
    
    // 创建信号量
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    // 创建全局并行
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, queue, ^{
        
        // 获取通知数据
        [self getNoticeData];
        
        dispatch_semaphore_signal(semaphore);
    });
    
    
    
    dispatch_group_async(group, queue, ^{
        
        // 获取通知数据
        [self getCountyListData];
        
        dispatch_semaphore_signal(semaphore);
    });
    
    
    
    
    dispatch_group_async(group, queue, ^{
        
        
        // 获取下级区域
        [self getLevelAreaData];
        
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_group_async(group, queue, ^{
        
        // 获取最近统计数据
        [self getRecentStatisticsDataWithDays:7];
        
        dispatch_semaphore_signal(semaphore);
    });
    
    dispatch_group_notify(group, queue, ^{
        // 三个请求对应三次信号等待
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
        
        
    });
    
    
}


#pragma mark - UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.titles.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *ID = @"homeCell";
    CHHomeViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:ID forIndexPath:indexPath];
    cell.imgName = [NSString stringWithFormat:@"sj_home_icon_%zd",indexPath.row+1];
    cell.titleName = self.titles[indexPath.row];
    cell.numLabel.text = self.resultArr[indexPath.row];
    return cell;
}

#pragma mark--UICollectionViewDelegateFlowLayout
////定义每个UICollectionView 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0,0);
}
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
// 两行之间的最小间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    //         if(indexPath.row == 1){
    //
    //            [[NSNotificationCenter defaultCenter] postNotificationName:@"changeToWXJL" object:nil];
    //            UINavigationController *nav = [self.tabBarController.viewControllers objectAtIndex:3];
    //            UIViewController *vc = nav.topViewController;
    //
    //            if ([vc isKindOfClass:[CHQueryViewController class]]) {
    //                [((CHQueryViewController *)vc) setMark:2];
    //            }
    //            self.tabBarController.selectedIndex = 3;
    //
    //
    //        }else{
    //
//    [MBProgressHUD showWarning:@"敬请期待"];
//
//    //        }
    
}

// 当选择某个选项时调用
- (void)dropdownMenu:(LMJDropdownMenu *)menu selectedCellNumber:(NSInteger)number
{
    if (menu == self.yearMenu) {
        CountyModel *model = self.citys[number];
        if (![self.areaid isEqualToString:model.areaid]) {
            [self.areanMenu hideDropDown];
            [self.areanMenu.mainBtn setTitle:@"选择区" forState:UIControlStateNormal];
            [self.areanMenu.mainBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        }
        self.areaid = model.areaid;
        [self getLowerCityListDataWithAreaid:model.areaid];
    }else if (menu == self.areanMenu){
        
        CountyModel *model = self.lowerCitys[number];
        self.areaid = model.areaid;
        [self.yearMenu hideDropDown];
    }
}




#pragma mark 检查版本
-(void)checkVersion
{
    NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
    [params setValue:leapAPPname forKey:@"appname"];
    
    [[Globle getInstance].service RequestWithServiceName:@"lbcp_getAppVersion" params:params httpMethod:@"POST" resultIsDictionary:YES completeBlock:^(id result) {
        
        NSLog(@"%@",result);
        NSDictionary *dic = (NSDictionary *)result;
        if(nil != dic)
        {
            [MBProgressHUD hideHUD];
            //获取本地版本
            self.remarksPath = dic[@"remarks"];
            NSString *localVersion = VersionCode;
            int localVersionNUm = (localVersion == nil ? -1 : [localVersion intValue]);
            //获取服务器版本
            NSString *serverVersion = [dic valueForKey:@"appversion"];
            int serverVersionNum = (serverVersion == nil ? -1 : [serverVersion intValue]);
            //判断是非升级
            if(localVersionNUm < serverVersionNum)
            {
                NSString *upgrade = [dic valueForKey:@"upgrade"];
                if([@"1" isEqualToString:upgrade])    //   强制升级
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                }
                else
                {
                    self.alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"有新的版本，请及时更新。" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定",@"取消", nil];
                }
                
                [self.alertView show];
                
            }
        }
    }];
    
}

#pragma mark - UIAlertView delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(alertView == self.alertView)
    {
        if(buttonIndex == 0)
        {
            NSString *urlStr = [NSString stringWithFormat:@"%@",self.remarksPath];
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];
        }
    }
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    NSLog(@"滚动了");
//
//    if (scrollView == self.queryScrollView) {
//
//        int tag = (int)scrollView.contentOffset.x/self.view.size.width +100 ;
//
//        UIButton *btn = (UIButton *)[self.queryView viewWithTag:tag];
//
//        _isSearchCompany = btn.tag == 100 ? YES : NO;
//        self.selectedBtn.enabled = YES;
//        btn.enabled = NO;
//        self.selectedBtn  = btn;
//
//        [UIView animateWithDuration:0.2 animations:^{
//            self.indicatorView.frame = CGRectMake(btn.x, CGRectGetMaxY(btn.frame), btn.w, 1);
//
//            [self.queryScrollView setContentOffset:CGPointMake((btn.tag - 100) *UIScreenW, 0) animated:YES];
//
//        }];
//    }
//}



- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self.rollView start];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getNoticeData) name:@"sendSuccessMessage" object:nil];
    
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.rollView stopTimer];
    
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    
}

- (UIStatusBarStyle)preferredStatusBarStyle {
    
    return UIStatusBarStyleLightContent;
    
}


-(void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    NSLog(@"主页销毁了");
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    NSLog(@"点击了");
}

@end
